package com.yofeedy.data;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.yofeedy.bean.UserFeeds;

public final class UserFeedDaoImpl implements UserFeedDao {

	public static UserFeedDaoImpl userFeedDaoImpl = null;

	private UserFeedDaoImpl() {
	}

	public static UserFeedDaoImpl getUserFeedDaoImpl() {
		if (userFeedDaoImpl == null) {
			userFeedDaoImpl = new UserFeedDaoImpl();
		}
		return userFeedDaoImpl;
	}

	private PersistenceManager getPersistenceManager() {
		return PMF.get().getPersistenceManager();
	}

	private User getCurrentUser() {
		UserService userService = UserServiceFactory.getUserService();
		return userService.getCurrentUser();
	}

	public List<UserFeeds> getUserFeeds() {

		PersistenceManager pm = getPersistenceManager();
		List<UserFeeds> userFeeds = null;
		try {
			if (getCurrentUser() != null) {
				Query query = pm.newQuery(UserFeeds.class);
				query.setFilter("userEmail == userEmailParam");
				query.declareParameters(String.class.getName()
						+ " userEmailParam");
				userFeeds = (List<UserFeeds>) query.execute(getCurrentUser()
						.getEmail());
				userFeeds.size();
			}
			// Add the default implementation when there is no feeds
			if (userFeeds == null || userFeeds.size() == 0) {
				userFeeds = new ArrayList<UserFeeds>();
				UserFeeds userFeed = new UserFeeds();
				userFeed.setFeedHeader("The Hindu");
				userFeed.setFeedURL("http://www.thehindu.com/?service=rss");
				userFeeds.add(userFeed);

				userFeed = new UserFeeds();
				userFeed.setFeedHeader("NDTV");
				userFeed.setFeedURL("http://feeds.feedburner.com/NdtvNews-TopStories");
				userFeeds.add(userFeed);

				userFeed = new UserFeeds();
				userFeed.setFeedHeader("CNN");
				userFeed.setFeedURL("http://rss.cnn.com/rss/edition.rss");
				userFeeds.add(userFeed);

				userFeed = new UserFeeds();
				userFeed.setFeedHeader("Reuters");
				userFeed.setFeedURL("http://feeds.reuters.com/reuters/INtopNews");
				userFeeds.add(userFeed);

			}

		} finally {
			pm.close();
		}
		return userFeeds;
	}

	public void saveUserFeeds(UserFeeds userFeed) {
		PersistenceManager pm = getPersistenceManager();
		try {
			if (getCurrentUser() != null) {
				userFeed.setUserEmail(getCurrentUser().getEmail());
				if (userFeed.getFeedHeader() != null
						&& userFeed.getFeedURL() != null) {
					pm.makePersistent(userFeed);
				}
			}

		} finally {
			pm.close();
		}
	}

}
